/**
 *
 * create---2018-6-22
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {Navigator} from "react-native-deprecated-custom-components";
import {
    ActivityIndicator,
    AsyncStorage,
    BackAndroid,
    DeviceEventEmitter,
    Image,
    Platform,
    StatusBar,
    StyleSheet,
    View
} from "react-native";
import TypeUtils from "./ipar/utils/TypeUtils";
import SlideMenu from "./ipar/menu/SlideMenu";
import Toast from 'react-native-easy-toast'
import SelectCountryPage from "./ipar/pages/common/SelectCountryPage";
import {StatusBarTextStyle} from "./ipar/custom/Navigation";
import I18n from './ipar/res/language/i18n'
import OrdersPage from "./ipar/pages/mePage/order/OrdersPage";
import SafeAreaView from 'react-native-safe-area-view';
import StyleUtils from "./ipar/res/styles/StyleUtils";
import UpgradeView from "./ipar/utils/UpgradeView";
import UmengPush from 'react-native-umeng-push';
import IparImageView from "./ipar/custom/IparImageView";
import IparNetwork, {SERVER_TYPE} from "./ipar/httpUtils/IparNetwork";
import CommonUtils from "./ipar/common/CommonUtils";
import WelcomePage from "./ipar/pages/WelcomePage";

export default class MainController extends Component {
    constructor(props) {
        super(props);

        this.state = {
            first: 0,
            componentName: '',
            component: null,
            loadingVisible: false,
        };
    }

    componentWillMount() {
        if (TypeUtils.getPhoneType() === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', onBack.bind(this));
        }
    };

    componentWillUnmount() {
        if (TypeUtils.getPhoneType() === 'android') {
            BackAndroid.removeEventListener('hardwareBackPress', onBack.bind(this));
        }
        this.deEmitter.remove();
        this.deEmitterLoading.remove();
        this.timer && clearTimeout(this.timer);
    };

    componentDidMount() {
        this.deEmitter = DeviceEventEmitter.addListener('toast', (massage) => {
            this.refs.toast.show(massage, 2000);
        });

        this.deEmitterLoading = DeviceEventEmitter.addListener('loading', (boold) => {
            if (this.state.loadingVisible !== boold) {
                this.pageIndex = this.oldPageIndex;
                this.setState({
                    loadingVisible: boold,
                })
            }
        });

        /**
         * 获取用户以前设置的语言
         */
        I18n.locale = 'en';
        AsyncStorage.getItem('lang', (error, result) => {
            if (result && result !== 'NULL') {
                I18n.locale = result;
            }
        });

        if (Platform.OS === 'ios')
            this.onLoad();
        else
            this.timer = setTimeout(() => this.onLoad(), 1000);

        //获取DeviceToken
//         UmengPush.getDeviceToken(deviceToken => {
//             console.log("deviceToken: ", deviceToken);
//         });
//
// //接收到推送消息回调
//         UmengPush.didReceiveMessage(message => {
//             console.log("didReceiveMessage:", message);
//         });
//
// //点击推送消息打开应用回调
//         UmengPush.didOpenMessage(message => {
//             console.log("didOpenMessage:", message);
//         });




    }


    onLoad() {
        AsyncStorage.getItem('country_id', (error, result) => {
            if (result) {
                this.setState({
                    componentName: 'WelcomePage',
                    component: WelcomePage,
                });
            } else {//第一次打开app
                this.setState({
                    componentName: 'SelectCountryPage',
                    component: SelectCountryPage,
                })
            }
        })
    }


    /**
     * init
     * @returns {*}
     */
    render() {
        const {componentName, component} = this.state;

        let navigator = component != null ? (
            <Navigator
                ref={'navigator'}
                //指定了默认的页面，也就是启动app之后会看到的第一屏，需要两个参数，name跟component
                initialRoute={{
                    name: componentName,
                    component: component,
                }}
                configureScene={(route) => {
                    //跳转的动画
                    let configure = Navigator.SceneConfigs.PushFromRight;
                    if (route.name === 'OrderPayPage' ||
                        route.name === 'ReturnOrdersPage' ||
                        route.name === 'RegisterIBMOnePage' ||
                        route.name === 'MandatoryProductPage' ||
                        route.name === 'OrderSuccessPage') {
                        return {
                            ...configure,
                            gestures: {},
                        };
                    } else {
                        return {
                            ...configure,
                        };
                    }


                }}
                renderScene={(route, navigator) => {
                    this._navigator = navigator;
                    let Component = route.component;
                    if (route.component) {
                        //返回页面的时候关闭loading
                        this.oldPageIndex = route.component;
                        if (this.pageIndex !== this.oldPageIndex && this.state.loadingVisible) {
                            this.setState({
                                loadingVisible: false,
                            })
                        }
                        return <Component  {...route.params} navigator={navigator}/>
                    }
                }}/>
        ) : <Image
            resizeMode="contain"
            style={{width: '100%', height: '100%', backgroundColor: '#ffffff', resizeMode: 'contain'}}
            source={require('./ipar/res/images/ic_welcome.png')}/>;
        return (<SafeAreaView style={StyleUtils.flex}>
                {/*status*/}
                <StatusBar
                    translucent={true}
                    backgroundColor={'transparent'}
                    barStyle={StatusBarTextStyle.white}
                />


                {navigator}


                {this.state.loadingVisible && <View style={styles.position}>

                    <View style={[{
                        backgroundColor: 'rgba(0, 0, 0, 0.25)'
                    }, styles.position,]}/>

                    <View style={[styles.position, StyleUtils.center]}>
                        <ActivityIndicator
                            size={'large'}
                            color={'white'}
                        />
                    </View>

                </View>}

                <Toast
                    position='center'
                    style={{backgroundColor: '#555555'}}
                    fadeInDuration={750}
                    ref="toast"/>

                <UpgradeView/>
            </SafeAreaView>

        );
    }


}

const styles = StyleSheet.create({
    position: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
    }

});

function onBack() {
    const nav = this._navigator;
    let routers = nav.getCurrentRoutes();
    let routersLen = routers.length;
    if (routersLen > 1) {

        //通过安卓手机点击返回按钮的时候如果用户在OrderPayPage的话不能返回。。。。。
        let name = routers[routersLen - 1].name;


        /**
         * 用户在OrdersPage点击返回的时候我们反倒第一页面(SlideMenu)
         */
        switch (name) {

            case 'OrderPayPage':
                nav.push({
                    component: OrdersPage,
                    name: 'OrdersPage',
                });
                break;
            case 'RegisterIBMOnePage':
                let destinationRoute1 = '';
                for (let i = routersLen - 1; i >= 0; i--) {
                    if (routers [i].name === "LoginPage") {
                        destinationRoute1 = routers[i];
                        nav.popToRoute(destinationRoute1);
                        break;
                    }
                }
                break;
            case 'OrdersPage':
            case 'OrderSuccessPage':
            case 'MandatoryProductPage':
            case 'ReturnOrdersPage':

                let destinationRoute = '';
                for (let i = routersLen - 1; i >= 0; i--) {
                    if (routers [i].name === "SlideMenu") {
                        destinationRoute = routers[i];
                        nav.popToRoute(destinationRoute);
                        break;
                    }
                }
                break;
            default: {
                nav.pop();
            }
        }

        return true;
    } else {
        //到了主页了
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
            //最近2秒内按过back键，可以退出应用。
            return false;
        }
        this.lastBackPressed = Date.now();
        DeviceEventEmitter.emit('toast', I18n.t('toast.onBack'));
        return true;

    }


}
